<template>
  <div class="Resgister">
    <head-title>注册</head-title>
    <logo></logo>
    <van-field
      v-model="username"
      label="用户名"
      placeholder="请输入用户名"
      @input="checkUsername"
      :error-message="usernameErrMes"
    />
    <van-field
      v-model="nickname"
      label="密码"
      placeholder="请输入昵称"
      :error-message="NicknameErrMes"
      @input="checkNickname"
    />
    <van-field
      v-model="password"
      type="password"
      label="密码"
      :error-message="PasswordErrMes"
      @input="checkPassword"
    />
    <shop-button @click.native="regsiter">注册</shop-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: "",
      password: "",
      nickname: "",
      usernameErrMes: "",
      NicknameErrMes: "",
      PasswordErrMes: "",
    };
  },
  methods: {
    checkUsername() {
      if (this.username == "") {
        this.usernameErrMes = "";
      } else {
        const reg = /^\d{3,12}$/;
        if (reg.test(this.username)) {
          this.usernameErrMes = "";
        } else {
          this.usernameErrMes = "用户名格式不正确";
        }
      }
    },
    checkNickname() {
      if (this.nickname == "") {
        this.NicknameErrMes = "";
      } else {
        const reg = /^[\u4e00-\u9fa5]{1,5}$/;
        if (reg.test(this.nickname)) {
          this.NicknameErrMes = "";
        } else {
          this.NicknameErrMes = "昵称格式不正确";
        }
      }
    },
    checkPassword() {
      if (this.password == "") {
        this.PasswordErrMes = "";
      } else {
        const reg = /^[a-z0-9]{3,12}$/;
        if (reg.test(this.password)) {
          this.PasswordErrMes = "";
        } else {
          this.PasswordErrMes = "密码格式不正确";
        }
      }
    },
    async regsiter() {
      if (
        this.password != "" &&
        this.username != "" &&
        this.nickname != "" &&
        this.usernameErrMes == "" &&
        this.NicknameErrMes == "" &&
        this.PasswordErrMes == ""
      ) {
        const res = await this.$axios.post("/register", {
          username: this.username,
          password: this.password,
          nickname: this.nickname,
        });
        this.$toast.success = "注册成功";
        this.$router.push({
          name: "login",
          params: { username: this.username, password: this.password },
        });
      } else {
        this.$toast.fail("注册信息有误");
      }
    },
  },
};
</script>

<style>
</style>